#include "StdAfx.h"
#include "AsioChannel.h"
#include "Log.h"

namespace ftp
{

AsioChannel::AsioChannel(SocketSPtr socket)
	: m_socket(socket)
{}
 
void AsioChannel::asyncWrite(const char* buffer, size_t bufferSize)
{
	m_socket->async_write_some(ba::buffer(buffer, bufferSize), boost::bind(&AsioChannel::handleDataWrote, this, ba::placeholders::error));
}

void AsioChannel::asyncRead()
{
	m_socket->async_read_some(ba::buffer(m_inBuffer), boost::bind(&AsioChannel::handleDataRead, this, ba::placeholders::error, ba::placeholders::bytes_transferred));
}

//private

void AsioChannel::handleDataWrote(const boost::system::error_code& e)
{
	bool ok = true;
	if (e)
	{
		LOG() << "Error on write: " << e.message() << std::endl; 
		ok = false;
	}

	if (m_sync)
		m_sync->onBytesWrote(ok);
}

void AsioChannel::handleDataRead(const boost::system::error_code& e, const size_t bytesRead)
{
	bool ok = true;
	if (e)
	{
		LOG() << "Error on read: " << e.message() << std::endl; 
		ok = false;
	}

	if (m_sync)
		m_sync->onBytesRead(ok, m_inBuffer, bytesRead);
}

} //ftp
